package com.mask.sca.auth.config;

import com.mask.sca.auth.entity.SecurityUser;
import com.mask.sca.auth.security.CustomUserDetailsService;
import com.mask.sca.auth.granter.SmsCodeTokenGranter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.TokenGranter;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
import org.springframework.http.ResponseEntity;
import com.mask.sca.auth.exception.CustomOauthException;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private CustomUserDetailsService userDetailsService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Bean
    public TokenStore tokenStore() {
        return new InMemoryTokenStore(); // 可替换为RedisTokenStore
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security
                .tokenKeyAccess("permitAll()")
                .checkTokenAccess("permitAll()")
                .allowFormAuthenticationForClients();
    }


    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        // 配置一个内存客户端，client_id=client, client_secret=secret
        clients.inMemory()
                .withClient("client")
                .secret(passwordEncoder.encode("secret"))
                .authorizedGrantTypes("password", "refresh_token", "sms_code")
                .scopes("all")
                .accessTokenValiditySeconds(36000)
                .refreshTokenValiditySeconds(864000);
    }


    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        System.out.println("AuthorizationServerConfig: configure endpoints, authenticationManager=" + authenticationManager + ", userDetailsService=" + userDetailsService);
        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        tokenEnhancerChain.setTokenEnhancers(
                Arrays.asList(tokenEnhancer(), jwtAccessTokenConverter()));
        endpoints
                .tokenEnhancer(tokenEnhancerChain)
                .authenticationManager(authenticationManager)
                .userDetailsService(userDetailsService)
                .tokenStore(tokenStore());
        // 注册自定义TokenGranter
        endpoints.tokenGranter(tokenGranter(endpoints));
        // 设置自定义异常翻译器，统一封装异常响应
        endpoints.exceptionTranslator(customWebResponseExceptionTranslator());
    }

    private TokenGranter tokenGranter(AuthorizationServerEndpointsConfigurer endpoints) {
        return new org.springframework.security.oauth2.provider.CompositeTokenGranter(java.util.Arrays.asList(
                endpoints.getTokenGranter(),
                new SmsCodeTokenGranter(authenticationManager, endpoints.getTokenServices(), endpoints.getClientDetailsService(), endpoints.getOAuth2RequestFactory(), redisTemplate)
        ));
    }

    /**
     * jwt格式封装token
     *
     * @return
     */
    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
        // 设置jwt加解密秘钥，不设置会随机一个
        jwtAccessTokenConverter.setSigningKey("OAuth2Constant.SIGN_KEY");
        return jwtAccessTokenConverter;
    }

    /**
     * token增强,添加一些元信息
     * 用户信息的补充
     *
     * @return TokenEnhancer
     */
    @Bean
    public TokenEnhancer tokenEnhancer() {
        return (accessToken, authentication) -> {
            final Map<String, Object> additionalInfo = new HashMap<>(10);
            SecurityUser user = (SecurityUser) authentication.getUserAuthentication().getPrincipal();
            if (user != null) {
                additionalInfo.put("userId", user.getId()); //用户id
                additionalInfo.put("userName", user.getUsername()); //用户名
                additionalInfo.put("userType", user.getUserType()); //用户类型
                additionalInfo.put("authStatus", user.getAuthStatus()); //用户审核状态
                additionalInfo.put("avatar", user.getAvatar()); //用户头像
                additionalInfo.put("sex", user.getSex()); //性别
                additionalInfo.put("nickName", user.getNickName());
                additionalInfo.put("birthday", user.getBirthday());
            }
            ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
            return accessToken;
        };
    }


    @Bean
    public WebResponseExceptionTranslator<OAuth2Exception> customWebResponseExceptionTranslator() {
        return e -> {
            Throwable cause = e.getCause() != null ? e.getCause() : e;
            CustomOauthException customException = new CustomOauthException(cause.getMessage());
            return ResponseEntity
                    .status(customException.getHttpErrorCode())
                    .body(customException);
        };
    }

    public static void main(String[] args) {
        PasswordEncoder passwordEncoder1 = new BCryptPasswordEncoder();
        String encode = passwordEncoder1.encode("123456");
        System.err.println(encode);
    }
} 